#pragma once
#include "Command.hpp"

class Client
{
public:
    Client(std::string ip = gdefaultip, uint16_t port = gdefaultport) :
    _port(port),
    _ip(ip),
    _isrunning(false)
    {
    }

    void InitClient()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            perror("socket error");
            return;
        }
        // 不需要自己绑定由OS自动绑定，避免多个应用冲突
        std::cout << "bind success" << std::endl;
    }
    void Start()
    {
        _isrunning = true;
        
        // 服务器死循环接受数据
        while (true)
        {
            std::cout<<"Please Enter#";
            std::string line;
            getline(std::cin,line);

            //发送
            struct sockaddr_in server_addr;
            server_addr.sin_family = AF_INET; // 保持一致性
            server_addr.sin_port = ::htons(_port);
            server_addr.sin_addr.s_addr = ::inet_addr(_ip.c_str());
            ssize_t n=::sendto(_sockfd, line.c_str(), line.size(), 0, CONV(&server_addr), sizeof(server_addr));
            if(n==-1)
            {
                perror("sendto error");
                exit(1);
            }
            // else 
            // {
            //     std::cout<<"send success"<<std::endl;
            // }
            
            //接收回显消息
            struct sockaddr_in recv_addr;
            socklen_t addr_len = sizeof(recv_addr);
            char buffer[1024];
            // 阻塞接受
            n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&recv_addr), &addr_len);
            buffer[n]=0;
            if (n == -1)
            {
                perror("recvfrom error");
                continue;
            }   
            std::cout<<buffer<<std::endl;

        }
    }

    ~Client()
    {
        if (_isrunning)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _port;  // 服务器未来的端口号
    std::string _ip; // 服务器所对应的IP
    bool _isrunning; // 客户端运行状态
};
